package com.atguigu.tingshu.album.job;

import cn.hutool.core.collection.CollectionUtil;
import com.atguigu.tingshu.album.mapper.TrackInfoMapper;
import com.atguigu.tingshu.album.service.VodService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author: atguigu
 * @create: 2024-10-21 14:27
 */
@Slf4j
@Component
public class ReviewResultTask {

    /**
     * corn表达式：秒 分 时 日 月 周 年
     */
    //@Scheduled(cron = "0/5 * * * * ?")
    //public void job1(){
    //  log.info("定时任务触发了");
    //}

    @Autowired
    private TrackInfoMapper trackInfoMapper;

    @Autowired
    private VodService vodService;

    /**
     * 定时获取声音审核结果，根据审核结果更新声音审核状态
     */
    @Scheduled(cron = "0/5 * * * * ?")
    public void reviewResultJob() {
        log.info("[专辑服务]定时审核音频审核结果开始.");
        //1. 查询审核状态为审核中的声音列表
        LambdaQueryWrapper<TrackInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TrackInfo::getStatus, SystemConstant.TRACK_STATUS_REVIEWING);
        queryWrapper.select(TrackInfo::getId, TrackInfo::getReviewTaskId);
        queryWrapper.last("limit 100");
        List<TrackInfo> trackInfoList = trackInfoMapper.selectList(queryWrapper);

        //2. 遍历列表，根据审核任务ID调用云点播平台，获取审核结果
        if (CollectionUtil.isNotEmpty(trackInfoList)) {
            trackInfoList.forEach(trackInfo -> {
                //3.1 调用云点播平台，获取审核结果
                String result = vodService.getReviewResult(trackInfo.getReviewTaskId());
                //3.2 根据审核结果更新声音表审核状态
                if (StringUtils.isNotBlank(result)) {
                    if ("pass".equals(result)) {
                        trackInfo.setStatus(SystemConstant.TRACK_STATUS_PASS);
                    } else if ("block".equals(result)) {
                        trackInfo.setStatus(SystemConstant.TRACK_STATUS_NO_PASS);
                    } else if ("review".equals(result)) {
                        trackInfo.setStatus(SystemConstant.TRACK_STATUS_MANUAL);
                    }
                    trackInfoMapper.updateById(trackInfo);
                }
            });
        }
    }
}
